import {Component, OnInit, AfterViewInit, ElementRef, Renderer2, ViewChild, OnDestroy} from '@angular/core';
import {ApiService} from "@core/services/http/api.service";
import {ApesMessageService} from "@shared/apes/message";
import {CompanyModalComponent} from "../company-modal/company-modal.component";
import {AnalysisService} from "../analysis.service";
import {UserAuthService} from "@core/services/user-auth.service";
import {Router} from "@angular/router";

@Component({
  selector: 'apes-door-control',
  templateUrl: './door-control.component.html',
  styleUrls: ['./door-control.component.scss']
})
export class DoorControlComponent implements OnInit, AfterViewInit, OnDestroy {
  @ViewChild(CompanyModalComponent,{static:true}) child: CompanyModalComponent;
  private timer;
  private timers;
  private timeres;
  // 时间相关
  todayTimes: Date;
  dateTimes: any[] = [];
  months: Date;
  dateMonths: any[] = [];
  // 每页显示多少条
  tablesIndex: number = 0;
  // 脑袋汇总
  headList: any[];
  titleData = {};

  barData: any[] = [];
  barTable: any[] = [];
  reportData: any[] = [];

  g2Data: any;
  chart: any;

  companyLocal = this.as.getLocalObj();
  companyData = [];
  company: any;
  userInfo = this.userAuthService.getUserInfoObj();
  keyNum: any = 0;
  clickTime: any;
  year: any;
  companyLogo: any;                               // 5e746d2839bf6200014e3b20
  logoTitle: any;
  host:any = window.location.host;                // test57-6060.jekunauto.cn
  // host:any = 'test57-6060.jekunauto.cn';                // test57-6060.jekunauto.cn

  constructor(private apiService: ApiService,
              private el: ElementRef,
              private renderer: Renderer2,
              private msg: ApesMessageService,
              private as: AnalysisService,
              private userAuthService: UserAuthService,
              private router: Router,) {
    if (this.companyLocal) {
      let company: any = this.companyLocal;
      let data = [];
      for (let item of company) {
        for (let list of item['array']) {
          data.push(list.id);
        }
      }
      this.company = this.as.unique(data);
    } else if (this.userInfo) {
    } else {
      this.router.navigateByUrl('/analysis/control/index');
    }

    let times = (1000 * 60) * 10;
    this.timer = setInterval(() => {
      this.titleData = {};
      this.barData = [];
      this.barTable = [];
      this.getHeadTop();
      this.getTablesList();
    }, times)

    this.timers = setInterval(() => {
      this.dateMonths = [];
      this.dateTimes = [];
      this.getMonths();
      this.getTodayTimes();
    }, 1000)

    this.timeres = setInterval(() => {
      this.reportData = [];
      this.pageList(this.barTable);
    }, 10000)
  }

  ngOnInit() {
    const date = new Date();
    this.year = date.getFullYear();
    this.as.getImges('如约车服1').then(value => {
      this.logoTitle = value;
      this.companyLogo = value ? 'https://'+this.host+'/fileserver/view/'+value : './assets/tmp/img/bi/swzx_02.png';
    });
    this.companyData = this.company;
    this.changeCompany(this.companyData);
  }

  changeCompany(e) {
    this.companyData = e;
    this.getHeadTop();
    this.headList = this.setHeadData();
    this.getTablesList();
    this.initFocus();
  }

  ngAfterViewInit() {
    const content = document.querySelector('#Boxs');
    const _body = document.querySelector('body');
    if( _body.clientWidth > 1920) {
      let _zoom = _body.clientWidth / content.clientWidth;
      setTimeout(() => {
        this.renderer.setStyle(content, 'zoom', _zoom);
      }, 100);
    }
  }

  // 返回上一页
  goBack($event: any) {
    let key = $event.button;
    if (key === 2) {
      history.go(-1);
      return false;
    }
  }

  private $(id) {
    return document.getElementById(id);
  }

  // 获取焦点
  initFocus() {
    this.$('system').focus();
  }

  getFocus() {
  }

  getKey($event, click?: any) {
    $event.preventDefault();
    let key = $event.keyCode;
    if (click === 1) {
      key = 0;
    }
    if (key === 0) {
      if(this.keyNum > 0) {
        this.onDblClick();
      }else {
        this.onClick();
      }
    }
    this.initFocus();
  }

  getMonths() {
    this.months = new Date();
    this.dateMonths = [];
    let shijian = 0;
    let riqi = 1;
    let newTimes;
    let month = this.months.toTimeString();
    for (let i = 0, len = month.length; i < len; i++) {
      newTimes = month.slice(shijian, riqi);
      this.dateMonths.push(newTimes);
      shijian++;
      riqi++;
    }
    this.dateMonths = this.dateMonths.filter((value) => value !== ":");
  }

  getTodayTimes() {
    this.todayTimes = new Date();
    this.dateTimes = [];
    let shijian = 0;
    let riqi = 1;
    let newTimes;
    let todayTime = this.todayTimes.toISOString();
    for (let i = 0, len = todayTime.length; i < len; i++) {
      newTimes = todayTime.slice(shijian, riqi);
      this.dateTimes.push(newTimes);
      shijian++;
      riqi++;
    }
    this.dateTimes = this.dateTimes.filter((value) => value !== "-");
  }

  // 脑袋汇总
  getHeadTop() {
    let data = {'interfaceMethod': 'ipmMgzzForAppService.getMGHead', 'pdata': {'companyId': this.companyData}};
    this.apiService.post('report.interface', {'body': JSON.stringify(data)}).subscribe(
      (resultData) => {
        // debugger;
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj)
            this.titleData = data;
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  setHeadData() {
    return [
      {
        titleData: [
          {lable: '今日总车流', feild: 'JRZCL'},
          {lable: '在店车流', feild: 'ZDCL'},
          {lable: '新增用户数', feild: 'XZYHS'},
          {lable: '新增VIP会员', feild: 'XZVIPS'},
          {lable: '服务业绩', feild: 'FWXSJE'},
          {lable: '年卡订单', feild: 'NKXSSL'},
          {lable: '年卡金额', feild: 'NKXSJE'},
          {lable: '年卡均价', feild: 'NKYJ'},
          {lable: '洗车台次', feild: 'XCTC'},
          {lable: '续卡会员', feild: 'RXKS'}
        ]
      }
    ]
  }

  // 上3表格
  reportList = [
    {
      api: 'ipmMgzzForAppService.getCJHJData',
      title: '到店未环检',
      tabWidth: '100%',
      flex: '4',
      margin: '0',
      background: '"assets/tmp/img/bi/mgzxA.png"',
      titleList: [
        {lable: '门店', feild: 'MDMC', width: '14%'},
        {lable: '接车人', feild: 'JIECR', width: '9%'},
        {lable: '车牌号', feild: 'CPHM', width: '13%', logo: 'TPLJ'},
        {lable: '指标', feild: 'ZB', width: '25%'},
        {lable: '时间', feild: 'SJ', width: '11%'}
      ]
    },
    {
      api: 'ipmMgzzForAppService.getTSJC',
      title: '36项未检测',
      tabWidth: '100%',
      flex: '2',
      margin: '20px',
      background: '"assets/tmp/img/bi/mgzxB.png"',
      titleList: [
        {lable: '接车人', feild: 'YGMC', width: '10%'},
        {lable: '车牌号', feild: 'CPHM', width: '13%', logo: 'TPLJ'},
        {lable: '等待时长', feild: 'SJ', width: '12%'}
      ]
    },
    {
      api: 'ipmMgzzForAppService.getDJSSH',
      title: '待技术审核',
      tabWidth: '100%',
      flex: '2',
      margin: '20px',
      background: '"assets/tmp/img/bi/mgzxC.png"',
      titleList: [
        {lable: '申请门店', feild: 'MDMC', width: '16%'},
        {lable: '申请人', feild: 'ZJSSHR', width: '9%'},
        {lable: '申请时长', feild: 'SJ', width: '14%'}
      ]
    }
  ];

  // 下左4表格
  tablesLeftList = [
    {
      api: 'ipmMgzzForAppService.xccsbc',
      title: '洗车超时补偿',
      tabWidth: '100%',
      titleWidth: '50%',
      titleList: [
        {lable: '门店名称', feild: 'MDMC', width: '14%'},
        {lable: '总补偿金额', feild: 'BCJE', width: '10%'}
      ]
    },
    {
      api: 'ipmMgzzForAppService.zdcsbc',
      title: '整单超时补偿',
      tabWidth: '100%',
      titleWidth: '50%',
      titleList: [
        {lable: '门店名称', feild: 'MDMC', width: '14%'},
        {lable: '总补偿金额', feild: 'BCJE', width: '10%'}
      ]
    }
  ];

  rightTableTop = [
    {
      api: 'ipmMgzzForAppService.getSGCS',
      title: '施工超时',
      tabWidth: '100%',
      titleWidth: '96%',
      titleList: [
        {lable: '门店', feild: 'MDMC', width: '16%'},
        {lable: '车牌号', feild: 'CPHM', width: '14%', logo: 'TPLJ'},
        {lable: '项目', feild: 'FWLXMC', width: '30%'},
        {lable: '超出时长', feild: 'JCBEYONDTIME', width: '11%'}
      ]
    },
    {
      api: 'ipmMgzzForAppService.getBPHCCS',
      title: '钣喷还车超时',
      tabWidth: '100%',
      titleWidth: '96%',
      titleList: [
        {lable: '内协门店', feild: 'MDMC', width: '14%'},
        {lable: '基地', feild: 'JDMDMC', width: '14%'},
        {lable: '基地接车人', feild: 'JIECR', width: '11%'},
        {lable: '车牌号', feild: 'CPHM', width: '13%', logo: 'TPLJ'},
        {lable: '时长', feild: 'SC', width: '16%'}
      ]
    }
  ]

  // 下右2表格
  tablesRightList = [
    // {
    //   api: 'ipmMgzzForAppService.getMDQKFX',
    //   title: '门店年卡转化率',
    //   tabWidth: '524px',
    //   titleList: [
    //     {lable: '门店', feild: 'MDMC', width: '160px'},
    //     {lable: '车流', feild: 'SL', width: '90px'},
    //     {lable: '新增VIP', feild: 'XZZS', width: '95px'},
    //     {lable: '年卡转化率', feild: 'NKZHL', width: '105px'}
    //   ]
    // },
    // {
    //   api: 'ipmMgzzForAppService.getGRNKZHL',
    //   title: '个人年卡转化率',
    //   tabWidth: '407px',
    //   titleList: [
    //     {lable: '接车人', feild: 'JIECR', width: '120px'},
    //     {lable: '接车台次', feild: 'JCSL', width: '85px'},
    //     {lable: '年卡数', feild: 'NKSL', width: '85px'},
    //     {lable: '转化率', feild: 'BL', width: '105px'}
    //   ]
    // },
    {
      api: 'ipmMgzzForAppService.queryCJCS',
      title: '拆检超时-基地',
      tabWidth: '98%',
      titleWidth: '50%',
      MDLXBJ: '1',
      titleList: [
        {lable: '基地', feild: 'MDMC', width: '14%'},
        {lable: '车牌号', feild: 'CPHM', width: '13%', logo: 'TPLJ'},
        {lable: '时长', feild: 'HS', width: '14%'},
        {lable: '状态', feild: 'YY', width: '12%'}
      ]
    },
    {
      api: 'ipmMgzzForAppService.queryCJCS',
      title: '拆检超时-门店',
      tabWidth: '98%',
      titleWidth: '50%',
      MDLXBJ: '0',
      titleList: [
        {lable: '门店', feild: 'MDMC', width: '14%'},
        {lable: '车牌号', feild: 'CPHM', width: '13%', logo: 'TPLJ'},
        {lable: '时长', feild: 'HS', width: '14%'},
        {lable: '状态', feild: 'YY', width: '12%'}
      ]
    },
  ];

  // 下右 创建柱形图
  getBar(bol ?: boolean) {
    if (bol) {
      this.chart.destroy();
    }

    let height: number;
    let fontSize: number;
    let fontSizeLabel: number;
    if( document.body.clientWidth < 1900 ) {
      height = 235;
      fontSize = 13;
      fontSizeLabel = 14;
    } else {
      height = 305;
      fontSize = 14;
      fontSizeLabel = 16;
    }

    let col1 = 'l(90) 0:rgb(255,163,2) 1:rgb(255,210,0)';       // 黄色渐变
    let col2 = 'l(90) 0:rgb(200,53,2) 1:rgb(236,105,65)';       // 蓝色渐变
    let ds = new DataSet();
    let dv = ds.createView().source(this.g2Data);
    dv.transform({
      type: 'fold',
      fields: ['保险到期', '保养到期', '报案跟踪', '二手车',
        '意向跟踪', '大金额订单', '隐患项目关怀', '未确认服务单'],
      key: 'key',                // key字段
      value: 'value'             // value字段
    });

    this.chart = new G2.Chart({
      container: 'container',
      forceFit: true,
      height: height,
      animate: false
    });

    this.chart.source(dv);

    this.chart.interval().position('key*value')
      .color('name', [col1, col2])
      .label('value', {
        textStyle: {
          fontSize: fontSizeLabel,          // 文本大小
          fill: '#fff',            // 文本颜色
          textBaseline: 'top',
        }
      })
      .adjust([{
        type: 'dodge',
        marginRatio: 1 / 5
      }]);

    // 底下文字样式
    this.chart.axis('key', {
      label: {
        autoRotate: false,
        textStyle: {
          fontSize: fontSize,                 // 文本大小
          textAlign: 'center',          // 文本对齐方式
          fill: '#fff',                 // 文本颜色
          rotate: 15,
        }

      },
      line: {
        lineWidth: 2,                   // 设置线的宽度
        stroke: '#07a1e4',              // 设置线的颜色
      },

    });

    // 左侧文字样式
    this.chart.axis('value', {
      label: {
        textStyle: {
          fontSize: fontSize,                 // 文本大小
          textAlign: 'right',          // 文本对齐方式
          fill: '#07a1e4'                 // 文本颜色
        }
      },
      line: {
        lineWidth: 2,                    // 设置线的宽度
        stroke: '#07a1e4',               // 设置线的颜色
      }
    });


    this.chart.tooltip(false);
    this.chart.legend(false);
    this.chart.render();

  }

  data = {
    "grand_total": {
      "意向跟踪": 0,
      "二手车": 0,
      "保险到期": 0,
      "保养到期": 0,
      "客诉跟踪": 0,
      "name": "two",
      "未确认服务单": 0,
      "年审到期": 0,
      "大金额订单": 0,
      "报案跟踪": 0,
      "隐患项目关怀": 0
    },
    "today_total": {
      "意向跟踪": 0,
      "二手车": 0,
      "保险到期": 0,
      "保养到期": 0,
      "客诉跟踪": 0,
      "name": "one",
      "未确认服务单": 0,
      "年审到期": 0,
      "大金额订单": 0,
      "报案跟踪": 0,
      "隐患项目关怀": 0
    },
    "unfollow_list": [
      {
        "employee_name": "无数据",
        "grand_total": 0,
        "today_total": 0
      }]
  };

  // 柱形图相关
  getTablesList() {
    let data = {'interfaceMethod': 'ipmMgzzForAppService.getGZ', 'pdata': {'companyId': this.companyData}};
    this.apiService.post('report.interface', {'body': JSON.stringify(data)}).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            this.data = JSON.parse(result.obj);
            this.barData = [];
            let data1 = this.data.today_total;
            this.barData.push(data1);
            let data2 = this.data.grand_total;
            this.barData.push(data2);
            let draw = true;
            if (!this.g2Data) {
              draw = false;
            }
            this.g2Data = this.barData;
            if (!draw) {
              this.getBar();
            } else {
              this.getBar(draw);
            }
            let tablelist = this.data.unfollow_list;
            this.barTable = tablelist;
            this.pageList(this.barTable);
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  pageList(arrData: any[]) {
    const count = arrData.length;
    this.reportData = [];
    let tempIndex = 0;
    for (let i = this.tablesIndex; i < count; i++) {
      if (tempIndex < 8) {
        this.reportData.push(arrData[i]);
      } else {
        break;
      }
      tempIndex++;
      this.tablesIndex++;
    }
    // console.log(this.reportData)
    //当数据遍历完 重新请求数据
    if (this.tablesIndex >= count) {
      this.tablesIndex = 0;
    }
  }

  onClick() {
    clearTimeout(this.clickTime);
    this.keyNum++;
    this.clickTime = setTimeout(()=>{
      this.keyNum = 0;
      this.router.navigateByUrl('/analysis/control/index');
    },500);
  }

  onDblClick() {
    clearTimeout(this.clickTime);
    this.child.isVisible = true;
    this.keyNum = 0;
  }

  ngOnDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
    }
    if (this.timers) {
      clearInterval(this.timers);
    }
    if (this.timeres) {
      clearInterval(this.timeres);
    }
  }
}
